package com.bdqn.t296.noso.config.shiro;

import com.bdqn.t296.noso.entity.Menu;
import com.bdqn.t296.noso.entity.Role;
import com.bdqn.t296.noso.entity.User;
import com.bdqn.t296.noso.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Set;

public class MyShiroRealm extends AuthorizingRealm {//安全数据源

    @Resource
    private UserService userService;

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用 MyShiroRealm.doGetAuthenticationInfo 获取身份信息！ ");
        //获得身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String loginname = token.getUsername();
        User user = userService.doLogin(loginname);
        if (user == null) {
            throw new UnknownAccountException(); //账号错误
        }
        if (user.getAvailable() == null || user.getAvailable().intValue() == 0) {
            throw new LockedAccountException(); //账号锁定
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,//身份(根据用户名查询数据库获得的用户)
                user.getPwd(),//凭证(查询数据库获得的密码)
                getName()//Realm 对象的名称
        );
        //返回身份信息
        return info;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用 MyShiroRealm.doGetAuthorizationInfo 获取权限信息！ ");
        //获得权限信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //动态授权
        Role role = user.getRole();
        System.out.println("shiro角色" + user.getRole().getRolename());
        if (role != null) {
            info.addRole(user.getRole().getRolename());
            Set<Menu> menus = role.getMenus();
            if (menus != null && menus.size() > 0) {
                for (Menu menu : menus) {
                    info.addStringPermission(menu.getId());
                    System.out.println("shiro角色地址" + menu.getHref());

                }
            }
        }
        return info;
    }
}
